package cn.iocoder.yudao.module.project.controller.admin.supplier;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.project.config.projectDefine.HTTP_STATUS.ERROR_STATUS;

import cn.iocoder.yudao.module.project.controller.admin.supplier.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.supplier.SupplierDO;
import cn.iocoder.yudao.module.project.service.supplier.SupplierService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 供应商信息")
@RestController
@RequestMapping("/project/supplier")
@Validated
public class SupplierController {

    @Resource
    private SupplierService supplierService;

    @PostMapping("/create")
    @Operation(summary = "创建供应商信息")
    // @PreAuthorize("@ss.hasPermission('project:supplier:create')")
    public CommonResult<String> createSupplier(@Valid @RequestBody SupplierSaveReqVO createReqVO) {
        return success(supplierService.createSupplier(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新供应商信息")
    // @PreAuthorize("@ss.hasPermission('project:supplier:update')")
    public CommonResult<Boolean> updateSupplier(@Valid @RequestBody SupplierSaveReqVO updateReqVO) {
        supplierService.updateSupplier(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除供应商信息")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('project:supplier:delete')")
    public CommonResult<Boolean> deleteSupplier(@RequestParam("id") String id) {
        supplierService.deleteSupplier(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得供应商信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('project:supplier:query')")
    public CommonResult<SupplierRespVO> getSupplier(@RequestParam("id") String id) {
        SupplierDO supplier = supplierService.getSupplier(id);
        return success(BeanUtils.toBean(supplier, SupplierRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得供应商信息分页")
    // @PreAuthorize("@ss.hasPermission('project:supplier:query')")
    public CommonResult<PageResult<SupplierRespVO>> getSupplierPage(@Valid SupplierPageReqVO pageReqVO) {
        PageResult<SupplierDO> pageResult = supplierService.getSupplierPage(pageReqVO);
        PageResult<SupplierRespVO> result = BeanUtils.toBean(pageResult, SupplierRespVO.class);
        if (null != result) {
            List<SupplierRespVO> list = result.getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (SupplierRespVO supplierRespVO : list) {
                    LocalDateTime createTime = supplierRespVO.getCreateTime();
                    LocalDateTime operatingTime = supplierRespVO.getOperatingTime();
                    String createTimeStr = DateUtil.format(createTime, "yyyy-MM-dd HH:mm:ss");
                    String operatingTimeStr = DateUtil.format(operatingTime, "yyyy-MM-dd");
                    supplierRespVO.setCreateTimeStr(createTimeStr);
                    supplierRespVO.setOperatingTimeStr(operatingTimeStr);
                }
            }
        }
        return success(result);
    }

    // @GetMapping("/export-excel")
    // @Operation(summary = "导出供应商信息 Excel")
    // @PreAuthorize("@ss.hasPermission('project:supplier:export')")
    // @ApiAccessLog(operateType = EXPORT)
    // public void exportSupplierExcel(@Valid SupplierPageReqVO pageReqVO,
    //           HttpServletResponse response) throws IOException {
    //     pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
    //     List<SupplierDO> list = supplierService.getSupplierPage(pageReqVO).getList();
    //     // 导出 Excel
    //     ExcelUtils.write(response, "供应商信息.xls", "数据", SupplierRespVO.class,
    //                     BeanUtils.toBean(list, SupplierRespVO.class));
    // }




    @Operation(summary = "导出供应商模板 Excel")
    @GetMapping(value = "/exportTemplate")
    public void exportTemplate(HttpServletResponse response){
        InputStream inputStream = null;
        String fileName = "供应商导入模板.xlsx";
        try {
            ClassPathResource classPathResource = new ClassPathResource("/template/供应商导入模板.xlsx");
            inputStream = classPathResource.getInputStream();
            Workbook excel = WorkbookFactory.create(inputStream);

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));;//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (Exception e) {
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @PostMapping("/importSupplier")
    @Operation(summary = "导入供应商 Excel")
    public CommonResult<Boolean> importSupplier(@RequestParam("file") MultipartFile file) {
        try {
            long start = System.currentTimeMillis();
            ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
            Sheet sheet = excelReader.getSheet();
            List<List<Object>> list = excelReader.read();

            if (CollectionUtil.isNotEmpty(list)) {
                if (list.size() > 2) {
                    List<SupplierDO> importDataList = new ArrayList<>();

                    // 从第二行开始读取
                    for(int i = 1; i < list.size(); i++){
                        SupplierDO supplierDO = new SupplierDO();
                        // 供应商编码
                        Object id = list.get(i).get(0);
                        if(id != null && !id.equals("")){
                            supplierDO.setId(id.toString());
                        }

                        // 供应商名称
                        Object name = list.get(i).get(1);
                        if(name != null && !name.equals("")){
                            supplierDO.setName(name.toString());
                        }

                        // // 录入人
                        // Object operator = list.get(i).get(2);
                        // if(operator != null && !operator.equals("")){
                        //     supplierDO.setOperator(operator.toString());
                        // }
                        //
                        // // 备注
                        // Object remark = list.get(i).get(3);
                        // if(remark != null && !remark.equals("")){
                        //     supplierDO.setRemark(remark.toString());
                        // }

                        // 导入时间
                        LocalDateTime today = LocalDateTimeUtils.getToday();
                        supplierDO.setOperatingTime(today);
                        supplierDO.setDeleted(false);
                        importDataList.add(supplierDO);
                    }

                    if (CollectionUtil.isNotEmpty(importDataList)) {
                        List<String> ids = importDataList.stream()
                                .map(c -> {
                                    return c.getId();
                                })
                                .distinct()
                                .collect(Collectors.toList());
                        Map<String, Object> params = new HashMap<>();
                        params.put("ids", ids);

                        // 查询已经存在的供应商数据,这些将不再写入库中
                        List<SupplierDO> savedList = supplierService.selectSavedList(params);
                        List<SupplierDO> updateList = new ArrayList<SupplierDO>();
                        List<SupplierDO> insertList = new ArrayList<SupplierDO>();

                        for (SupplierDO record : importDataList) {
                            boolean issaved = false;

                            if (null != savedList && savedList.size() > 0) {
                                for (SupplierDO saved : savedList) {
                                    if (
                                            saved.getId().equals(record.getId())
                                    ) {
                                        record.setId(saved.getId());
                                        updateList.add(record);
                                        issaved = true;
                                        break;
                                    }
                                }

                            }

                            if (!issaved) {
                                insertList.add(record);
                            }
                        }

                        supplierService.insertRecord(insertList);
                        supplierService.updateRecord(updateList);
                        System.out.println("取excel完毕：" +(System.currentTimeMillis() - start)+"}毫秒");
                    }
                }

            }
        } catch (Exception e) {
            throw new ServiceException(ERROR_STATUS, "导入供应商失败");
        }
        return success(true);
    }

}